/**
 * 测试用例批量编辑接口测试用例
 *
 * Created by raquelmao on 2020/06/10.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmarks = [require('./../../../benchmark/generate-tests/self_designed')];

module.exports = describe('/PUT functions/:id/tests.json', function () {
  const administrator = new Administrator();
  let project = {};
  const newUserIds = [];
  function url(functionId) {
    return `/functions/${functionId}/tests.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((res) => {
        project = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');

  // 正常批量编辑测试用例
  it('it should edit tests', function (done) {
    let projectVersion;
    let allFunctions;
    const newKey = 'stubs.stub.0.%.@value';
    const newValue = randomstring.generate(5);
    project.createRandomVersion()
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllTests(benchmarks[0]);
      })
      .then(() => projectVersion.getAllFunctions(benchmarks[0]))
      .then((res) => {
        allFunctions = res;
        return project.creator.login();
      })
      .then(() => {
        const promises = [];
        allFunctions.forEach((func) => {
          if (func.functionId) {
            promises.push(new Promise((resolve) => {
              chai.request(uri)
                .put(url(func.functionId))
                .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
                .query({ key: newKey, value: newValue })
                .end((err, res) => {
                  res.should.have.status(200);
                  resolve();
                });
            }));
          }
        });
        return Promise.all(promises);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });
});
